package com.github.phoenics.militia.bazookaFx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.phoenics.militia.bazookaFx.dao.AppTableDao;
import com.github.phoenics.militia.bazookaFx.domain.entity.AppTable;
import com.github.phoenics.militia.bazookaFx.domain.entity.SchemaTablesView;
import com.github.phoenics.militia.bazookaFx.domain.enums.TableType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Phoenics Chow
 * on 2019年01月31日
 */
@Service
public class AppTableService extends ServiceImpl<AppTableDao, AppTable> {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AppTableService.class);
    @Autowired
    SchemaTablesViewService schemaTablesViewService;

    @Transactional
    public void saveTree(String schemaName,Long appId){
        QueryWrapper<SchemaTablesView> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("table_schema",schemaName);
        Map<String,Long> modelMaps=schemaTablesViewService.list(queryWrapper).stream().map(i->{
            String ty=i.getTableType();
            TableType tt=TableType.BASETABLE;
            if(ty.equals("VIEW")){
                tt=TableType.VIEW;
            }
            AppTable appTable=new AppTable();
            appTable.setAppId(appId);
            appTable.setTableType(tt);
            appTable.setTableName(i.getTableName());
            appTable.setTableCnName(i.getTableComment());
            appTable.setTableComment(i.getTableComment());
            appTable.setCreateTime(i.getCreateTime());
            this.save(appTable);
            return appTable;
        }).collect(Collectors.toMap(AppTable::getTableName, AppTable::getAppId, (key1, key2) -> key2));


    }
}
